package com.erp.shop.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ruoyi.ae.api.RemoteAeCategoryService;
import com.ruoyi.gather.api.domain.*;
import com.ruoyi.gather.api.domain.dto.ErpBrandCountDto;
import com.ruoyi.shop.api.domain.ErpStoreCategoryBrand;
import com.erp.shop.domain.bo.ErpStoreCategoryBrandBo;
import com.erp.shop.domain.vo.ErpStoreCategoryBrandVo;
import com.erp.shop.mapper.ErpSellerStoreEmpowerMapper;
import com.erp.shop.mapper.ErpStoreCategoryBrandMapper;
import com.erp.shop.service.IErpStoreCategoryBrandService;
import com.ruoyi.common.core.core.domain.DictResult;
import com.ruoyi.common.core.domain.PageQuery;
import com.ruoyi.common.core.domain.R;
import com.ruoyi.common.core.web.oldPage.TableDataInfo;

import com.ruoyi.common.core.utils.oldUtils.StringUtils;
import com.ruoyi.common.security.utils.SecurityUtils;
import com.ruoyi.gather.api.RemoteCollectProductService;
import com.ruoyi.gather.api.RemoteSellerProductService;
import com.ruoyi.gather.api.RemoteProductCategoryBrandService;
import com.ruoyi.shop.api.domain.ErpSellerStoreEmpower;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 店铺可用类目品牌Service业务层处理
 *
 * @author erp
 * @date 2023-07-21
 */
@RequiredArgsConstructor
@Service
public class ErpStoreCategoryBrandServiceImpl implements IErpStoreCategoryBrandService {
    private final ErpSellerStoreEmpowerMapper erpSellerStoreEmpowerMapper;
    private final ErpStoreCategoryBrandMapper baseMapper;
    @Resource
    RemoteProductCategoryBrandService remoteProductCategoryBrandService;
    @Resource
    ErpStoreCategoryBrandMapper erpStoreCategoryBrandMapper;
    @Resource
    RemoteCollectProductService remoteCollectProductService;
    @Resource
    RemoteAeCategoryService remoteAeCategoryService;


    /**
     * 查询店铺可用类目品牌
     */
    @Override
    public ErpStoreCategoryBrandVo queryById(Long id) {
        return baseMapper.selectVoById(id);
    }

    /**
     * 查询店铺可用类目品牌列表
     */
    @Override
    public TableDataInfo<ErpStoreCategoryBrandVo> queryPageList(ErpStoreCategoryBrandBo bo, PageQuery pageQuery) {
        LambdaQueryWrapper<ErpStoreCategoryBrand> lqw = buildQueryWrapper(bo);
        Page<ErpStoreCategoryBrandVo> result = baseMapper.selectVoPage(pageQuery.build(), lqw);
        return TableDataInfo.build(result);
    }

    /**
     * 查询店铺可用类目品牌列表
     */
    @Override
    public List<ErpStoreCategoryBrandVo> queryList(ErpStoreCategoryBrandBo bo) {
        LambdaQueryWrapper<ErpStoreCategoryBrand> lqw = buildQueryWrapper(bo);
        return baseMapper.selectVoList(lqw);
    }

    private LambdaQueryWrapper<ErpStoreCategoryBrand> buildQueryWrapper(ErpStoreCategoryBrandBo bo) {
        Map<String, Object> params = bo.getParams();
        LambdaQueryWrapper<ErpStoreCategoryBrand> lqw = Wrappers.lambdaQuery();
        lqw.eq(bo.getStoreId() != null, ErpStoreCategoryBrand::getStoreId, bo.getStoreId());
        lqw.like(StringUtils.isNotBlank(bo.getBrandName()), ErpStoreCategoryBrand::getBrandName, bo.getBrandName());
        lqw.eq(bo.getBrandId() != null, ErpStoreCategoryBrand::getBrandId, bo.getBrandId());
        lqw.like(StringUtils.isNotBlank(bo.getCategoryCnName()), ErpStoreCategoryBrand::getCategoryCnName,
                bo.getCategoryCnName());
        lqw.like(StringUtils.isNotBlank(bo.getCategoryEnName()), ErpStoreCategoryBrand::getCategoryEnName,
                bo.getCategoryEnName());
        lqw.eq(bo.getCategoryId() != null, ErpStoreCategoryBrand::getCategoryId, bo.getCategoryId());
        lqw.eq(StringUtils.isNotBlank(bo.getCategoryLevel()), ErpStoreCategoryBrand::getCategoryLevel,
                bo.getCategoryLevel());
        lqw.eq(StringUtils.isNotBlank(bo.getRevision()), ErpStoreCategoryBrand::getRevision, bo.getRevision());
        return lqw;
    }

    /**
     * 新增店铺可用类目品牌
     */
    @Override
    public Boolean insertByBo(ErpStoreCategoryBrandBo bo) {
        ErpStoreCategoryBrand add = BeanUtil.toBean(bo, ErpStoreCategoryBrand.class);
        validEntityBeforeSave(add);
        boolean flag = baseMapper.insert(add) > 0;
        if (flag) {
            bo.setId(add.getId());
        }
        return flag;
    }

    /**
     * 修改店铺可用类目品牌
     */
    @Override
    public Boolean updateByBo(ErpStoreCategoryBrandBo bo) {
        ErpStoreCategoryBrand update = BeanUtil.toBean(bo, ErpStoreCategoryBrand.class);
        validEntityBeforeSave(update);
        return baseMapper.updateById(update) > 0;
    }

    /**
     * 保存前的数据校验
     */
    private void validEntityBeforeSave(ErpStoreCategoryBrand entity) {
        // TODO 做一些数据校验,如唯一约束
    }

    /**
     * 批量删除店铺可用类目品牌
     */
    @Override
    public Boolean deleteWithValidByIds(Collection<Long> ids, Boolean isValid) {
        if (isValid) {
            // TODO 做一些业务上的校验,判断是否需要校验
        }
        return baseMapper.deleteBatchIds(ids) > 0;
    }

    /**
     * @Description: 查询用户授权店铺列表
     * @Author: j.zh
     * @Date: 2024/7/4
     * @return
     * @Version: 4.2.0
    **/
    public List<ErpSellerStoreEmpower> getEmpowerList() {
        if (SecurityUtils.getUserId() == 1l){
            // 超级管理员
            return erpSellerStoreEmpowerMapper.selectList();
        }
        return erpSellerStoreEmpowerMapper.selectList(new LambdaQueryWrapper<ErpSellerStoreEmpower>()
                .eq(ErpSellerStoreEmpower::getUserId, SecurityUtils.getUserId())
                .eq(ErpSellerStoreEmpower::getIsEmpower, 1));
    }

    /**
     * @Description: 查询店铺可用类目品牌列表
     * @Author: j.zh
     * @Date: 2024/7/4
     * @param storeId
     * @return
     * @Version: 4.2.0
    **/
    @Override
    public Map<String, Object> getBrandListByStoreId(Long storeId) {
        Map<String, Object> map = new HashMap<>();
        List<ErpProductBrand> brandList = new ArrayList<>();
        List<Long> longList = new ArrayList<>();

        Long userId = null;
        try {
            userId = SecurityUtils.getUserId();
        } catch (NullPointerException e) {
            //空指针异常，代表未登录
            ErpSellerStoreEmpower store = erpSellerStoreEmpowerMapper.selectById(storeId);
            if (Objects.isNull(store)) {
                return null;
            }
            userId = store.getUserId();
        }

        // 超级管理员
        if (userId == 1l) {
            // 查询所有品牌
            R<Object> productBrandListObject = remoteProductCategoryBrandService.selectProductBrandAllList();
            String productBrandListString = JSONObject.toJSONString(productBrandListObject.getData());
            List<ErpProductBrand> list = JSONArray.parseArray(productBrandListString, ErpProductBrand.class);
            for (ErpProductBrand entity : list) {
                longList.add(entity.getId());
            }
            map.put("brandList", list);
            map.put("brandIdList", longList);
        } else {
            LambdaQueryWrapper<ErpStoreCategoryBrand> lqw = Wrappers.lambdaQuery();
            lqw.select(ErpStoreCategoryBrand::getBrandId, ErpStoreCategoryBrand::getBrandName,
                    ErpStoreCategoryBrand::getBrandCnName);
            lqw.eq(ErpStoreCategoryBrand::getStoreId, storeId);
            lqw.groupBy(ErpStoreCategoryBrand::getBrandId);
            List<ErpStoreCategoryBrand> list = baseMapper.selectList(lqw);

            for (ErpStoreCategoryBrand brand : list) {
                // 根据品牌名称查询erp系统对应品牌
                ErpProductBrand productBrandSel = new ErpProductBrand();
                productBrandSel.setBrandName(brand.getBrandCnName());
                R<Object> productBrandObject = remoteProductCategoryBrandService.selectProductBrandInfo(productBrandSel);
                String productBrandString = JSONObject.toJSONString(productBrandObject.getData());
                ErpProductBrand entity = JSONObject.parseObject(productBrandString, ErpProductBrand.class);
//                ErpProductBrand entity = erpProductBrandMapper.selectOne(new LambdaQueryWrapper<ErpProductBrand>()
//                        .eq(ErpProductBrand::getBrandName, brand.getBrandCnName()));
                if (entity != null) {
                    brandList.add(entity);
                    longList.add(entity.getId());
                }
            }
            // 查询无需授权品牌

            ErpProductBrand productBrandSel = new ErpProductBrand();
            productBrandSel.setEmpower(0);
            R<Object> productBrandListObject = remoteProductCategoryBrandService.selectProductBrandListInfo(productBrandSel);
            String productBrandListString = JSONObject.toJSONString(productBrandListObject.getData());
            List<ErpProductBrand> productBrandList = JSONArray.parseArray(productBrandListString, ErpProductBrand.class);
//            List<ErpProductBrand> productBrandList = erpProductBrandMapper
//                    .selectList(new LambdaQueryWrapper<ErpProductBrand>().eq(ErpProductBrand::getEmpower, 0));
            if (productBrandList.size() > 0) {
                for (ErpProductBrand productBrand : productBrandList) {
                    longList.add(productBrand.getId());
                }
            }
            map.put("brandList", brandList);
            map.put("brandIdList", longList);
        }
        return map;
    }

    /**
     * @Description: 查询可用类目品牌列表
     * @Author: j.zh
     * @Date: 2024/7/4
     * @return
     * @Version: 4.2.0
     **/
    @Override
    public Map<String, Object> getBrandList() {
        // 只查询有上架商品的品牌

        R<Object> brandAndProductCountObject = remoteCollectProductService.getBrandAndProductCount();
        if (brandAndProductCountObject.getCode() != 200){
            return null;
        }
        String brandAndProductCountStr = JSONObject.toJSONString(brandAndProductCountObject.getData());
        List<ErpBrandCountDto> dtoList = JSONArray.parseArray(brandAndProductCountStr, ErpBrandCountDto.class);

        List<Long> brandIdList = dtoList.stream().map(e -> e.getBrandId())
                .collect(Collectors.toList());
//        List<ErpProductBrand> brandList = dtoList.stream().map(e -> e.getProductBrand())
//                .collect(Collectors.toList());
//        List<Integer> productCountList = dtoList.stream().map(e -> e.getBrandProductCount())
//                .collect(Collectors.toList());

        Map<String, Object> map = new HashMap<>();
        map.put("brandList", dtoList);
        map.put("brandIdList", brandIdList);
//        map.put("productCountList", productCountList);

        return map;
    }

    @Override
    public Object getCatrgoryListByStoreId(Long storeId) {

        LambdaQueryWrapper<ErpStoreCategoryBrand> lqw = Wrappers.lambdaQuery();
        lqw.select(ErpStoreCategoryBrand::getCategoryId, ErpStoreCategoryBrand::getCategoryCnName);
        lqw.eq(ErpStoreCategoryBrand::getStoreId, storeId);
        lqw.ne(ErpStoreCategoryBrand::getBrandId, 201512802);
        lqw.groupBy(ErpStoreCategoryBrand::getCategoryId);
        List<ErpStoreCategoryBrand> list = baseMapper.selectList(lqw);

        List<DictResult> res = new ArrayList<DictResult>();
        for (ErpStoreCategoryBrand erpStoreCategoryBrand : list) {
            DictResult result = new DictResult();
            result.setLabel(erpStoreCategoryBrand.getCategoryCnName());
            result.setValue(erpStoreCategoryBrand.getCategoryId() + "");
            res.add(result);
        }

        return res;
    }

    @Override
    public R<Object> queryStoreBrand(Long categoryId,String collectProductId, Long storeId) {
        //获取商品眼神表示护具
        ErpCollectProductExpand productExpand = new ErpCollectProductExpand();
        productExpand.setCollectProductId(Long.valueOf(collectProductId));
        R<Object> expandObject = remoteCollectProductService.getCollectProductExpandInfo(productExpand);
        if (expandObject.getCode() == 200){
            String expandString = JSONObject.toJSONString(expandObject.getData());
            productExpand = JSONObject.parseObject(expandString, ErpCollectProductExpand.class);
        }else {
            //为了测试发布
            productExpand = new ErpCollectProductExpand();
        }

        //查找店铺中该类目是否有品牌，如果没有品牌则重新拉取一次
        List<ErpStoreCategoryBrand> brandList = baseMapper.selectList(
                new LambdaQueryWrapper<ErpStoreCategoryBrand>()
                        .eq(ErpStoreCategoryBrand::getStoreId, storeId)
                        .eq(ErpStoreCategoryBrand::getCategoryId, categoryId)
        );
        if (brandList.size() == 0) {
            //调取接口，重新设置
            R<Object> brandR = remoteAeCategoryService.getBrandByIdInnerAuth(categoryId, storeId);
            JSONObject brando = JSONObject.parseObject((String) brandR.getData());
            String aeopAttributeDto = brando.getJSONObject("aliexpress_category_redefining_getchildattributesresultbypostcateidandpath_response")
                    .getJSONObject("result")
                    .getJSONObject("attributes")
                    .getString("aeop_attribute_dto");
            List<Aliexpress.AttributeDto> attributeDtoList = JSONArray.parseArray(aeopAttributeDto, Aliexpress.AttributeDto.class);
            List<Aliexpress.ValueVo> values = new ArrayList<>();
            for (Aliexpress.AttributeDto attributeDto : attributeDtoList) {
                Long nameId = attributeDto.getId();
                if (nameId.equals(2l)) {

                    List<Aliexpress.AttrValueDto> attrValueDtoList = attributeDto.getValues().getAeopAttrValueDto();
                    if (attrValueDtoList != null) {
                        for (Aliexpress.AttrValueDto attrValueDto : attrValueDtoList) {
                            Aliexpress.ValueVo valueVo = new Aliexpress.ValueVo();

                            Map valueNames = JSONObject.parseObject(attrValueDto.getNames(), Map.class);
                            String enValueName = (String) valueNames.get("en");
                            String zhValueName = (String) valueNames.get("zh");

                            valueVo.setAttr_value_id(attrValueDto.getId());
                            valueVo.setZhName(zhValueName);
                            valueVo.setAttr_value(enValueName);
                            values.add(valueVo);
                        }
                    }
                }
            }
            for (Aliexpress.ValueVo value : values) {
                ErpStoreCategoryBrand brand = new ErpStoreCategoryBrand();
                brand.setStoreId(storeId);
                brand.setBrandCnName(value.getZhName());
                brand.setBrandId(value.getAttr_value_id());
                brand.setBrandName(value.getAttr_value());
                brand.setCategoryId(categoryId);
                erpStoreCategoryBrandMapper.insertOrUpdate(brand);
            }
        }

        Integer flag = null;
        ErpStoreCategoryBrand storeBrand = new ErpStoreCategoryBrand();
        //店铺可用品牌
        List<String> storeBrandList = baseMapper.queryStoreBrand(categoryId, storeId);
        //店铺泛品牌
        List<String> fanStoreBrandList = baseMapper.queryFanStoreBrand(categoryId, storeId);
        String nonwBrand = "NONE(AE存量)*******";
        String fanStoreBrand = null;
        if (fanStoreBrandList.size() > 0) {
            //有泛品牌，获得第一个
            fanStoreBrand = fanStoreBrandList.get(0);
        }


//        ErpSellerProductExpand productExpand = erpSellerProductExpandMapper.selectOne(
//                new LambdaQueryWrapper<ErpSellerProductExpand>()
//                        .eq(ErpSellerProductExpand::getSellerProductId, sellerProductId)
//        );

        Long brandId = productExpand.getBrandId();
        if (Objects.isNull(brandId)) {
            //没有品牌
            //查看是否有泛品牌且是否可用里面有泛品牌
            if (ObjectUtils.isNotNull(fanStoreBrand) && storeBrandList.contains(fanStoreBrand)) {
                //有
                storeBrand = baseMapper.selectOne(
                        new LambdaQueryWrapper<ErpStoreCategoryBrand>()
                                .eq(ErpStoreCategoryBrand::getBrandCnName, fanStoreBrand)
                                .eq(ErpStoreCategoryBrand::getCategoryId, categoryId)
                                .eq(ErpStoreCategoryBrand::getStoreId, storeId)
                                .last("limit 1")
                );
            } else if (Objects.isNull(storeBrand)) {
                //没有的话用none
                storeBrand = baseMapper.selectOne(
                        new LambdaQueryWrapper<ErpStoreCategoryBrand>()
                                .eq(ErpStoreCategoryBrand::getBrandCnName, nonwBrand)
                                .eq(ErpStoreCategoryBrand::getCategoryId, categoryId)
                                .eq(ErpStoreCategoryBrand::getStoreId, storeId));
            } else {
                //两者都无，用品牌（随机）
                storeBrand = baseMapper.selectOne(
                        new LambdaQueryWrapper<ErpStoreCategoryBrand>()
                                .eq(ErpStoreCategoryBrand::getCategoryId, categoryId)
                                .eq(ErpStoreCategoryBrand::getStoreId, storeId)
                                .last("limit 1"));
            }
        } else {
            //有品牌
            R<Object> productBrandObject = remoteProductCategoryBrandService.getProductBrandById(brandId);
            String productBrandString = JSONObject.toJSONString(productBrandObject.getData());
            ErpProductBrand brand = JSONObject.parseObject(productBrandString, ErpProductBrand.class);
            String brandName = brand.getBrandName();
            //1、确认这个品牌是否在可用品牌中
            if (storeBrandList.contains(brand.getBrandName())) {
                //在，使用这个
                storeBrand = baseMapper.selectOne(
                        new LambdaQueryWrapper<ErpStoreCategoryBrand>()
                                .eq(ErpStoreCategoryBrand::getBrandCnName, brandName)
                                .eq(ErpStoreCategoryBrand::getCategoryId, categoryId)
                                .eq(ErpStoreCategoryBrand::getStoreId, storeId));
            } else {
                //2、如果不在，使用none
                storeBrand = baseMapper.selectOne(
                        new LambdaQueryWrapper<ErpStoreCategoryBrand>()
                                .eq(ErpStoreCategoryBrand::getBrandCnName, nonwBrand)
                                .eq(ErpStoreCategoryBrand::getCategoryId, categoryId)
                                .eq(ErpStoreCategoryBrand::getStoreId, storeId));
                if (Objects.isNull(storeBrand) && ObjectUtils.isNotNull(fanStoreBrand)) {
                    //3、如果没有none，用泛品牌
                    storeBrand = baseMapper.selectOne(
                            new LambdaQueryWrapper<ErpStoreCategoryBrand>()
                                    .eq(ErpStoreCategoryBrand::getBrandCnName, fanStoreBrand)
                                    .eq(ErpStoreCategoryBrand::getCategoryId, categoryId)
                                    .eq(ErpStoreCategoryBrand::getStoreId, storeId));
                }
            }

        }

        if (Objects.isNull(storeBrand)) {
            return R.fail("没有符合要求的品牌");
        } else {
            return R.ok(storeBrand);
        }

    }


}
